#include "muduo/proto/dispatcher.h"
#include "muduo/proto/codec.h"
#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpClient.h"
#include "muduo/net/EventLoopThread.h"
#include "muduo/base/CountDownLatch.h"

#include "requst.pb.h"
#include <iostream>
#include <memory>
#include <string>
#include<unistd.h>
class TcpClient
{
public:
    typedef std::shared_ptr<google::protobuf::Message> MessagePtr;
    typedef std::shared_ptr<cqy::AddResponse> AddResponsePtr;
    typedef std::shared_ptr<cqy::TranslateResponse> TranslateResponsePtr;
    TcpClient(const std::string &ip, int port) : _latch(1), _client(_loopthread.startLoop(), muduo::net::InetAddress(ip, port), "Client"),
                                        _dispatcher(std::bind(&TcpClient::onUnknownMessage, this, std::placeholders::_1,
                                                              std::placeholders::_2, std::placeholders::_3)),
                                        _codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher,
                                                         std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {
        // 注册消息处理回调
        _dispatcher.registerMessageCallback<cqy::TranslateResponse>(std::bind(&TcpClient::onTranslate, this,
                                                                              std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        _dispatcher.registerMessageCallback<cqy::AddResponse>(std::bind(&TcpClient::onAdd, this,
                                                                        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        // 设置连接处理回调
        _client.setConnectionCallback(std::bind(&TcpClient::onConnection, this, std::placeholders::_1));
        // 设置消息回调链
        _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &_codec,
                                             std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }
    void connect()
    {
        _client.connect(); // 建立连接
        _latch.wait();     // 阻塞等待连接
    }
    void Translate(const std::string &msg)
    {
        cqy::TranslateRequest req;
        req.set_msg(msg);
        send(&req);
    }
    void Add(int num1,int num2)
    {
        cqy::AddRequest req;
        req.set_num1(num1);
        req.set_num2(num2);
        send(&req);
    }

private:
    bool send(const google::protobuf::Message * message)
    {
        if(_conn->connected())
        {
            _codec.send(_conn,*message);
            return true;
        }
        return false;
    }
    void onUnknownMessage(const muduo::net::TcpConnectionPtr &conn, const MessagePtr &message, muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected())
        {
            LOG_INFO << "connect success";
            _conn=conn;
            _latch.countDown();//关闭阻塞
        }
        else
        {
            LOG_INFO << "connect close";
            _conn.reset();//连接关闭
        }
    }
    void onTranslate(const muduo::net::TcpConnectionPtr &conn, const TranslateResponsePtr &message, muduo::Timestamp)
    {
        LOG_INFO<<"翻译结果为："<<message->msg();
    }
    void onAdd(const muduo::net::TcpConnectionPtr &conn, const AddResponsePtr &message, muduo::Timestamp)
    {
        LOG_INFO<<"相加结果为："<<message->result();
    }

private:
    muduo::CountDownLatch _latch;            // 实现同步的
    muduo::net::EventLoopThread _loopthread; // 事件监控
    muduo::net::TcpConnectionPtr _conn;      // 客户端对应的连接
    muduo::net::TcpClient _client;           // 客户端
    ProtobufDispatcher _dispatcher;          // 请求分发器对象--向其注册请求处理函数
    ProtobufCodec _codec;                    // 协议处理器，针对不同的请求使用不同的处理方法
};
int main()
{
    TcpClient client("127.0.0.1",8080);
    client.connect();
    client.Translate("Hello");
    client.Add(10,20);
    sleep(1);
    return 0;
}